package com.yjh.common.other;

import com.yjh.common.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    // 拦截所有请求，验证Token
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();

        if (requestURI.contains("/admin/ral/login") || requestURI.contains("/admin/ral/register")) {
            return true; // 直接放行登录和注册请求
        }

        // 设置响应字符编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 1. 从请求头中获取Token（前端需在请求头中携带Token，键为Authorization）
        String token = request.getHeader("Authorization");

        // 2. 检查Token是否存在
        if (token == null || token.isEmpty()) {
            response.setStatus(401); // 401：未授权
            response.getWriter().write("请先登录");
            return false; // 拦截请求
        }

        // 3. 处理Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        try {
            // 4. 从Token中解析用户名
            String username = JwtUtil.extractUsername(token);

            // 5. 验证Token有效性
            if (!JwtUtil.validateToken(token, username)) {
                response.setStatus(401);
                response.getWriter().write("Token无效或已过期");
                return false;
            }

            // 6. 从Token中获取用户ID并存储到request中
            String userId = JwtUtil.extractUserId(token);
            if (userId != null && !userId.isEmpty()) {
                request.setAttribute("userId", userId);
            }

            // 7. 存储用户名到request中（可选）
            request.setAttribute("username", username);

            // 8. Token有效，放行请求
            return true;

        } catch (Exception e) {
            // Token解析失败（如格式错误、签名错误）
            response.setStatus(401);
            response.getWriter().write("Token无效");
            return false;
        }
    }
}

